﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Huirui.Cavan.Domain.Seedwork;
using Huirui.Cavan.Domain.MainBoundedContext.SearchModule;
using Huirui.Cavan.Application.Seedwork;
using Huirui.Cavan.Domain.MainBoundedContext.StockModule;
using Huirui.Cavan.Application.MainBoundedContext.SystemModule;
using Spring.Context.Support;
using Huirui.Cavan.Core.Extension;
using Huirui.Cavan.Domain.MainBoundedContext.SystemModule;

namespace Huirui.Cavan.Application.MainBoundedContext.StockModule
{
    public class StockInOutTypeAppService : BaseAppService<StockInOutType, StockInOutTypeSearch, IStockInOutTypeRepository>, IStockInOutTypeAppService
    {
        private IEmployeeAppService EmployeeAppService { get; set; }

        public BoolGenericResult<StockInOutType> Edit(StockInOutType entity)
        {
            this.SpringContext = ContextRegistry.GetContext();
            BoolGenericResult<StockInOutType> result = new BoolGenericResult<StockInOutType>();
            if (entity.IsNull())
            {
                throw new ArgumentNullException("");
            }
            this.EmployeeAppService = this.SpringContext.GetObject(SystemModuleConst.EMPLOYEEAPPSERVICE) as IEmployeeAppService;
            Employee employee = this.EmployeeAppService.GetBySearch(SearchFactory.CreateEmployeeSearch(SecurityAppService.UserAccount.Id)).FirstOrDefault();
            StockManager stockManager = new StockManager(employee);

            StockInOutType oldStockInOutType = this.Repository.Get(entity.Id);
            if (oldStockInOutType.IsNull())
            {
                result = stockManager.AddStockInOutType(entity.Name, entity.IsIn, entity.FromAccount, entity.IsCostAccounting);
                if (result.IsSuccess)
                    return base.Add(result.Object);
            }
            else
            {
                result = stockManager.UpdateStockInOutType(oldStockInOutType, entity.Name, entity.IsIn, entity.FromAccount, entity.IsCostAccounting);
                if (result.IsSuccess)
                    return base.Update(result.Object);
            }
            return result;
        }
    }
}
